import threading
class ThreadSafeCache:
    def __init__(self):
        self.cache = {}
        self.lock = threading.Lock()

    def get(self, key):
        with self.lock:
            return self.cache.get(key)

    def set(self, key, value):
        with self.lock:
            self.cache[key] = value

    def delete(self, key):
        with self.lock:
            if key in self.cache:
                del self.cache[key]

    def clear(self):
        with self.lock:
            self.cache.clear()


# 使用示例
cache = ThreadSafeCache()


def cache_worker(worker_id):
    for i in range(100):
        key = f"key_{worker_id}_{i}"
        cache.set(key, f"value_{worker_id}_{i}")
        # 模拟偶尔的读取
        if i % 10 == 0:
            print(f"Worker {worker_id} got: {cache.get(key)}")


threads = []
for i in range(5):
    t = threading.Thread(target=cache_worker, args=(i,))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

print(f"Final cache size: {len(cache.cache)}")  # 应该是500